/**
 * 404页面脚本
 */

(function() {
  'use strict';

  console.log('[404页面] 脚本加载');

  // 等待DOM加载
  document.addEventListener('DOMContentLoaded', function() {
    console.log('[404页面] 页面初始化');

    // 获取DOM元素
    const backHomeBtn = document.getElementById('backHomeBtn');
    const goBackBtn = document.getElementById('goBackBtn');
    const notFoundImage = document.getElementById('notFoundImage');
    const fallbackIllustration = document.getElementById('fallbackIllustration');

    // 检测图片是否加载成功
    if (notFoundImage) {
      notFoundImage.onerror = function() {
        console.log('[404页面] 404.png未找到，显示后备样式');
        notFoundImage.style.display = 'none';
        if (fallbackIllustration) {
          fallbackIllustration.classList.add('show');
        }
      };

      // 检查图片是否已经加载失败
      if (notFoundImage.complete && notFoundImage.naturalHeight === 0) {
        notFoundImage.style.display = 'none';
        if (fallbackIllustration) {
          fallbackIllustration.classList.add('show');
        }
      }
    }

    // 返回首页按钮
    if (backHomeBtn) {
      backHomeBtn.addEventListener('click', function() {
        console.log('[404页面] 返回首页');
        // 返回主页（文件页面）
        // 检测当前路径，确定正确的返回路径
        const isInPagesDir = window.location.pathname.includes('/pages/');
        window.location.href = isInPagesDir ? '../index.html' : 'index.html';
      });
    }

    // 返回上一页按钮
    if (goBackBtn) {
      goBackBtn.addEventListener('click', function() {
        console.log('[404页面] 返回上一页');
        // 如果有历史记录，返回上一页
        if (window.history.length > 1) {
          window.history.back();
        } else {
          // 否则返回首页
          const isInPagesDir = window.location.pathname.includes('/pages/');
          window.location.href = isInPagesDir ? '../index.html' : 'index.html';
        }
      });
    }

    console.log('[404页面] 初始化完成');
  });
})();
